package com.mijie.homi.service.common;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.mijie.exception.PermissionDeniedException;
import com.mijie.exception.RecordNotFoundException;
import com.mijie.homi.dao.commom.ReviewDao;
import com.mijie.homi.domain.commom.Review;
import com.mijie.homi.service.notify.NotifyUserAgent;
import com.mijie.homi.util.ServerHelper;

public abstract class AbstractEventService implements EventService{
	
	@Autowired
	private ReviewDao reviewDao ;
	@Autowired
	private NotifyUserAgent notifyUserAgent;
	@Autowired
	private CommentService commentService;
	
	private Logger logger = Logger.getLogger(getClass());
	
	public abstract Review.Module getModule() ;
	
	private void doNotify(Review review){
		notifyUserAgent.sendReviewNotify(getModule(), review);
	}

	@Transactional(rollbackFor={Exception.class})
	public int newReview(Review review) throws RecordNotFoundException {
		int receiver = 0;
		boolean isOldVersionApiCall = review.getReceiver()!=0;
		//review.getReferId()==0相当于旧版的评论，不为0相当于旧版的评论回复
		if(review.getReferId()==0){
			if(isOldVersionApiCall){
				//兼容旧版
				receiver = review.getReceiver();
			}else{
				//新版评论
				receiver = getOwner(review.getEventId());
			}
		}else{
			Review r =  getReview(review.getReferId());
			if(isOldVersionApiCall){
				//兼容旧版
				receiver = review.getReceiver();
			}else{
				//新版评论
				receiver = r.getReviewer();
			}
			review.setRootId(r.getRootId()==0?r.getId():r.getRootId());
		}
		review.setReceiver(receiver);
		int succ = reviewDao.newReview(getModule(), review);
		if(succ>0){
			increNumOfReview(review.getEventId());
			if(receiver != review.getReviewer())
				doNotify(review);
		}
		return succ;
	}

	public Review getReview(int id) throws RecordNotFoundException {
		Review review =  reviewDao.getReview(getModule(), id);
		if(review==null) throw new RecordNotFoundException(id);
		return review;
	}

	public abstract int getOwner(long eventId) throws RecordNotFoundException;
	
	protected abstract int increNumOfReview(long eventId);
	
	protected abstract int decreNumOfReview(long eventId);
	
	@Transactional(rollbackFor={Exception.class})
	public  int deleteReview(long eventId, int id, int operator) 
			throws RecordNotFoundException,PermissionDeniedException{
		int eventOwner = getOwner(eventId);
		int succ = reviewDao.deleteReview(getModule(), eventId, id, eventOwner==operator?null:operator);
		if(succ>0) decreNumOfReview(eventId);
		return succ;
	}

	public List<Review> listReview(long eventId, int offset, int limit) {
		return reviewDao.listReview(getModule(), eventId, offset, limit);
	}
	
}
